package com.geeklan.smart.ui.pet;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.PetInfo;
import com.geeklan.smart.data.remote.oss.FileUploader;
import com.geeklan.smart.data.remote.oss.UploadCallback;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.ActivityEditPetBinding;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.dialog.DateBottomSheetDialog;
import com.geeklan.smart.ui.dialog.EditTextAlertDialog;
import com.geeklan.smart.ui.dialog.PetSexBottomSheetDialog;
import com.geeklan.smart.ui.dialog.PetWeightBottomSheetDialog;
import com.geeklan.smart.ui.settings.UpdatePersonalDataActivity;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;
import com.geeklan.smart.utils.AssetsImagePathReader;
import com.geeklan.smart.utils.DateUtils;
import com.geeklan.smart.utils.ImagePathUtils;
import com.geeklan.smart.utils.ThreadTask;

import java.util.List;

import gun0912.tedimagepicker.builder.TedImagePicker;

public class EditPetActivity extends BaseActivity<ActivityEditPetBinding> {
    private PetInfo petInfo;
    private PetViewModel petViewModel;

    @Override
    protected ActivityEditPetBinding initBinding() {
        return ActivityEditPetBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        petInfo = (PetInfo) getIntent().getSerializableExtra("pet_info");

        Glide.with(this).load(petInfo.getPic()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivHead);
        mBinding.tvAge.setText(String.valueOf(DateUtils.calculateAge(petInfo.getBirthday())));
        mBinding.tvNickname.setText(petInfo.getName());
        mBinding.tvType.setText(petInfo.getVariety());
        mBinding.tvWeight.setText(String.format("%.1f", Float.parseFloat(petInfo.getWeight())));
        initSexUi();

        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);

        petViewModel.getDelPetLiveData().observe(this, response -> {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
            finish();
        });

        petViewModel.getAddPetErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });


        petViewModel.getUpdatePetLiveData().observe(this, response -> {
            dismiss();
        });
        petViewModel.getUpdatePetErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            dismiss();
        });
    }

    private void initSexUi() {
        switch (petInfo.getSex()) {
            case 1:
                mBinding.tvSex.setText("GG-公");
                break;
            case 3:
                mBinding.tvSex.setText("绝育GG-公");
                break;
            case 2:
                mBinding.tvSex.setText("MM-母");
                break;
            case 4:
                mBinding.tvSex.setText("绝育MM-母");
                break;
        }
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.llHead.setOnClickListener(v -> {
            checkAndRequestPermissions();
        });
        mBinding.llNikename.setOnClickListener(v -> {
            EditTextAlertDialog editTextAlertDialog = new EditTextAlertDialog(this, getString(R.string.update_name));
            editTextAlertDialog.setPositiveButtonText(getString(R.string.ok));
            editTextAlertDialog.setHint(petInfo.getName());
            editTextAlertDialog.setOnPositiveButtonClickListener(v1 -> {
                editTextAlertDialog.dismiss();
                String nickname = editTextAlertDialog.getContentText();
                if(TextUtils.isEmpty(nickname)) {
                    Toast.makeText(this,"请输入宠物名称",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(nickname.length() > 20) {
                    Toast.makeText(this,"宠物名称不能超过20字",Toast.LENGTH_SHORT).show();
                    return;
                }

                petInfo.setName(nickname);
                mBinding.tvNickname.setText(nickname);
                loading();
                petViewModel.updatePet(petInfo);
            });
            editTextAlertDialog.show();
        });
        mBinding.llWeight.setOnClickListener(v -> {
            PetWeightBottomSheetDialog petWeightBottomSheetDialog = new PetWeightBottomSheetDialog(this);
            petWeightBottomSheetDialog.setOnBackListener(weight -> {
                petInfo.setWeight(String.valueOf(weight));
                mBinding.tvWeight.setText(petInfo.getWeight());
                loading();
                petViewModel.updatePet(petInfo);
            });
            petWeightBottomSheetDialog.show();
        });
        mBinding.llSex.setOnClickListener(v -> {
            PetSexBottomSheetDialog petSexBottomSheetDialog = new PetSexBottomSheetDialog(this);
            petSexBottomSheetDialog.setOnBackListener(petSex -> {
                petInfo.setSex(petSex);
                initSexUi();
                loading();
                petViewModel.updatePet(petInfo);
            });
            petSexBottomSheetDialog.show();
        });

        mBinding.llAge.setOnClickListener(v -> {
            DateBottomSheetDialog dateBottomSheetDialog = new DateBottomSheetDialog(this);
            dateBottomSheetDialog.setCurrentDate(petInfo.getBirthday());
            dateBottomSheetDialog.setCancelableOutside(true); // 点击背景关闭
            dateBottomSheetDialog.setOnDateSelectedListener((year, month, day) -> {
                String brithday = year + "-" + month + "-" + day;
                mBinding.tvAge.setText(String.valueOf(DateUtils.calculateAge(brithday)));
                petInfo.setBirthday(brithday);
                dateBottomSheetDialog.dismiss();
                loading();
                petViewModel.updatePet(petInfo);
            });
            dateBottomSheetDialog.show();
        });
        mBinding.tvDelete.setOnClickListener(v -> {
            petViewModel.deletePet(petInfo);
        });
        mBinding.llCase.setOnClickListener(v -> {
            CaseListActivity.startActivity(this, petInfo.getId());
        });
        mBinding.llType.setOnClickListener(v -> {
            SelectPetActivity.startActivity(this, true);
        });
    }

    private void checkAndRequestPermissions() {
        if (!PermissionManager.hasPermissions(this, PermissionManager.REQUIRED_PERMISSIONS)) {
            requestPermissions(PermissionManager.REQUIRED_PERMISSIONS, PERMISSION_REQ_ID);
        } else {
            showSelectPhotoDialog();
        }
    }

    private void showSelectPhotoDialog() {
        TedImagePicker.with(this)
                .start(uri -> {
                    loading();
                    Glide.with(this).load(uri).apply(RequestOptions.circleCropTransform()).into(mBinding.ivHead);
                    uploadHead(uri);
                });
    }

    private void uploadHead(Uri headUri){
        FileUploader.uploadFile(this, ImagePathUtils.getImagePath(this, headUri), new UploadCallback() {
            @Override
            public void onUploadSuccess(String fileUrl) {
                petInfo.setPic(fileUrl);
                petViewModel.updatePet(petInfo);
            }
            @Override
            public void onUploadFailure() {
                dismiss();
                Toast.makeText(EditPetActivity.this,"上传失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK) {
            String typeName = data.getStringExtra("typeName");
            int petType = data.getIntExtra("petType",1);
            petInfo.setPetType(petType);
            petInfo.setVariety(typeName);
            mBinding.tvType.setText(typeName);
            loading();
            petViewModel.updatePet(petInfo);
        }
    }


    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, PetInfo petInfo) {
        Intent intent = new Intent(context, EditPetActivity.class);
        intent.putExtra("pet_info", petInfo);
        context.startActivity(intent);
    }
}